<?php
namespace app\common\service\appeal;
use app\common\cache\appeal\ShopOrderAppealCache;
use app\common\model\appeal\ShopOrderAppealModel;
use app\common\service\file\SettingService;
use think\facade\Db;

/**
 * 申诉中心
 */
class ShopOrderAppealService
{
    /**
     * 添加、修改字段
     * @var array
     */
    public static $edit_field = [
            'id' => '',
        'is_disable' => '',
        'merchant_id' => '',
        'shop_order_id' => '',
        'shop_order_on' => '',
        'setting_appeal_type_id' => '',
        'is_terminal' => '',
        'member_account_id' => '',
        'status' => '',
        'is_tip' => '',
        'remark' => '',
        'content' => '',
        'image_ids' => '',
    ];
    /**
     * 申诉中心列表
     *
     * @param array  $where 条件
     * @param int    $page  页数
     * @param int    $limit 数量
     * @param array  $order 排序
     * @param string $field 字段
     *
     * @return array
     */
    public static function list($where = [], $page = 1, $limit = 10,  $order = [], $field = '')
    {
        $model = new ShopOrderAppealModel();
        $pk = $model->getPk();
        if (empty($field)) {
            $field = 'id,is_disable,create_time,update_time,merchant_id,shop_order_id,shop_order_on,setting_appeal_type_id,is_terminal,member_account_id,status,is_tip,remark';
        }
        if (empty($order)) {
            $order = ['status'=>'asc','create_time'=>'asc',$pk => 'desc'];
        }
        if ($page == 0 || $limit == 0) {
            return $model->field($field)->where($where)->order($order)->select()->toArray();
        }
        $with = ['appealType'=>function($query){
            $query->field('id,code,title');
        }];
        $count = $model->where($where)->count();
        $pages = ceil($count / $limit);
        $list = $model->with($with)->field($field)->where($where)->page($page)->limit($limit)->order($order)->select()->toArray();
        return compact('count', 'pages', 'page', 'limit', 'list');
    }
    /**
     * 申诉中心信息
     *
     * @param int  $id   申诉中心id
     * @param bool $exce 不存在是否抛出异常
     *
     * @return array|Exception
     */
    public static function info($id, $exce = true)
    {
        $model = new ShopOrderAppealModel();
        $with = ['message'=>function ($query) {
            $query->order('create_time','asc');
        },'appealType'=>function($query){
            $query->field('id,code,title');
        }];
        $info = $model->with($with)->find($id);
        if (empty($info)) {
            if ($exce) {
                exception('申诉不存在：' . $id);
            }
            return [];
        }
        $info = $info->toArray();
        $merchantId = mer_id();
        foreach ($info['message'] as $key=>$val){
            //查询商家图片
            if($val['image_ids'] && $val['is_terminal']==1){
                $files = Db::name('merchant_file')
                    ->where('is_disable',0)
                    ->where('is_delete',0)
                    ->where('file_id','in',explode(',',$val['image_ids']))
                    ->when(isset($val['mer_id']), function($query) use ($val) {
                        $query->where('mer_id', $val['mer_id']);
                    })
                    ->select()
                    ->toArray();
                foreach ($files as $k=>$v){
                    $files[$k]['file_url'] = SettingService::fileUrl($v);
                }
                $info['message'][$key]['image_ids'] =$files;
            }else if($val['image_ids'] && $val['is_terminal']!=1){
                $files = Db::name('file')
                    ->where('is_disable',0)
                    ->where('is_delete',0)
                    ->where('file_id','in',explode(',',$val['image_ids']))
                    ->select()
                    ->toArray();
                foreach ($files as $k=>$v){
                    $files[$k]['file_url'] = SettingService::fileUrl($v);
                }
                $info['message'][$key]['image_ids'] =$files;
            }
        }
        return $info;
    }
    /**
     * 根据订单ID查询申诉信息
     *
     * @param int  $id   申诉中心id
     * @param bool $exce 不存在是否抛出异常
     *
     * @return array|Exception
     */
    public static function infoByOrderID($order_id, $member_id=null)
    {
        $model = new ShopOrderAppealModel();
        $with = ['message'=>function ($query) {
            $query->order('create_time','asc');
        },'appealType'=>function($query){
            $query->field('id,code,title');
        }];
        $info = $model
            ->with($with)
            ->where('shop_order_id',$order_id)
            ->when($member_id,function ($query)use($member_id){
                $query->where('member_id',$member_id);
            })
            ->order(['status' => 'asc', 'create_time' => 'desc'])
            ->find();
        if (empty($info)) {
            return null;
        }
        $info = $info->toArray();
        foreach ($info['message'] as $key=>$val){
            //查询商家图片
            if($val['image_ids'] && $val['is_terminal']==1){
                $files = Db::name('merchant_file')
                    ->where('is_disable',0)
                    ->where('is_delete',0)
                    ->where('file_id','in',explode(',',$val['image_ids']))
                    ->when(isset($val['mer_id']), function($query) use ($val) {
                        $query->where('mer_id', $val['mer_id']);
                    })
                    ->select()
                    ->toArray();
                foreach ($files as $k=>$v){
                    $files[$k]['file_url'] = SettingService::fileUrl($v);
                }
                $info['message'][$key]['image_ids'] =$files;
            }else if($val['image_ids'] && $val['is_terminal']!=1){
                $files = Db::name('file')
                    ->where('is_disable',0)
                    ->where('is_delete',0)
                    ->where('file_id','in',explode(',',$val['image_ids']))
                    ->select()
                    ->toArray();
                foreach ($files as $k=>$v){
                    $files[$k]['file_url'] = SettingService::fileUrl($v);
                }
                $info['message'][$key]['image_ids'] =$files;
            }
        }
        return $info;
    }
    /**
     * 申诉中心添加
     *
     * @param array $param 申诉中心信息
     *
     * @return array|Exception
     */
    public static function add($param)
    {
        $model = new ShopOrderAppealModel();
        $pk = $model->getPk();
        unset($param[$pk]);
        $param['create_uid']  = user_id();
        $param['create_time'] = datetime();
        $model->save($param);
        $id = $model->$pk;
        if (empty($id)) {
            exception();
        }
        $param[$pk] = $id;
        return $param;
    }
     /**
     * 申诉中心修改
     *
     * @param int|array $ids   申诉中心id
     * @param array     $param 申诉中心信息
     *
     * @return array|Exception
     */
    public static function edit($ids, $param = [])
    {
        $model = new ShopOrderAppealModel();
        $pk = $model->getPk();
        unset($param[$pk], $param['ids']);
        $param['update_uid']  = user_id();
        $param['update_time'] = datetime();
        $res = $model->where($pk, 'in', $ids)->update($param);
        if (empty($res)) {
            exception();
        }
        $param['ids'] = $ids;
        ShopOrderAppealCache::del($ids);
        return $param;
    }
    /**
     * 申诉中心删除
     *
     * @param array $ids  申诉中心id
     * @param bool  $real 是否真实删除
     *
     * @return array|Exception
     */
    public static function dele($ids, $real = false)
    {
        $model = new ShopOrderAppealModel();
        $pk = $model->getPk();
        if ($real) {
            $res = $model->where($pk, 'in', $ids)->delete();
        } else {
            $update = delete_update();
            $res = $model->where($pk, 'in', $ids)->update($update);
        }
        if (empty($res)) {
            exception();
        }
        $update['ids'] = $ids;
        ShopOrderAppealCache::del($ids);
        return $update;
    }

    /**
     * 申诉回复
     * @Author: 易军辉
     * @DateTime:2024-06-28 17:44
     * @param $ids
     * @param $param
     * @return array|mixed
     * @throws \think\Exception
     */
    public static function reply($id, $param = [])
    {
        $model = new ShopOrderAppealModel();
        $pk = $model->getPk();
        $info = $model->find($id);
        if (empty($info)) {
            exception('申诉不存在：' . $id);
            return [];
        }
        //获取图片
        $image_ids = "";
        if(isset($param['image_ids']) && $param['image_ids']){
            foreach ($param['image_ids'] as $key=>$val){
                if($image_ids!=""){
                    $image_ids .=",";
                }
                $image_ids .=$val['file_id'];
            }
        }
        $message_data = array(
            'shop_order_appeal_id'=>$info['id'],//申诉表ID
            'is_terminal'=>$param['is_terminal'],//终端：1、商家端 2、买家端
            'merchant_id'=>$info['merchant_id'],//商家ID
            'member_account_id'=>$info['member_account_id'],//接单账号ID
            'member_id'=>$info['member_id'],//买家ID
            'content'=>$param['content'],//内容
            'image_ids'=>$image_ids,//截图id(多个逗号隔开)
            'create_uid'=>mer_user_id(),//添加用户id
            'create_time'=>date('Y-m-d H:i:s'),//创建时间
        );
        $res = Db::name('shop_order_appeal_message')->insert($message_data);
        if(!$res){
            exception('系统繁忙，请稍后再试');
        }
        if($info['status'] == 0){
            $info['status'] = 1;
            $info->save();
        }
        return $param;
    }
    /**
     * 申诉完结
     *
     * @param array $ids  申诉中心id
     * @param array $is_terminal 终端：1、商家端 2、买家端
     *
     * @return array|Exception
     */
    public static function end($ids,$is_terminal=1)
    {
        $merchantId = 0;
        $memberId = 0;
        $create_uid = 0;
        if($is_terminal ==1){
            $merchantId = mer_id(true);
            $create_uid = mer_user_id(true);
        }else if($is_terminal ==2){
            $memberId = member_id(true);
            $create_uid = $memberId;
        }else if($is_terminal ==3){
            $create_uid = user_id(true);
        }

        $model = new ShopOrderAppealModel();
        $pk = $model->getPk();
        $list = $model
            ->where($pk, 'in', $ids)
            ->when($merchantId>0, function($query) use ($merchantId) {
                $query->where('merchant_id', $merchantId);
            })
            ->when($memberId>0, function($query) use ($memberId) {
                $query->where('member_id', $memberId);
            })
            ->field('id,merchant_id,member_account_id,member_id')
            ->select();
        if(count($list)<=0){
            exception('未查询到申诉订单');
        }
        $id_s = array_column($list->toArray(),'id');
        //修改申诉状态
        $res = $model->where($pk, 'in',$id_s )->update([
            'status'=>2,
            'update_time'=>date('Y-m-d H:i:s'),
            'update_uid'=>$create_uid
        ]);
        if (empty($res)) {
            exception();
        }
        //写入日志
        $message_data = [];
        foreach ($list as $key=>$val){
            $message_data[] = array(
                'shop_order_appeal_id'=>$val['id'],//申诉表ID
                'is_terminal'=>$is_terminal,//终端：1、商家端 2、买家端
                'merchant_id'=>$val['merchant_id'],//商家ID
                'member_account_id'=>$val['member_account_id'],//接单账号ID
                'member_id'=>$val['member_id'],//买家ID
                'content'=>'已主动关闭申诉',//内容
                'create_uid'=>$create_uid,//添加用户id
                'create_time'=>date('Y-m-d H:i:s'),//创建时间
            );
        }
        $res = Db::name('shop_order_appeal_message')->insertAll($message_data);
        $update['ids'] = $id_s;
        ShopOrderAppealCache::del($id_s);
        return $update;
    }
}
